//
// Created by ChenJi on 2021/4/4.
//

#include <string.h>
#include "string_library.h"

char const itoa_index[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

uint8_t string_buf[30];

uint8_t myitoa(int32_t num, uint8_t *str, uint8_t radix) {
    unsigned unum;
    uint8_t i = 0, j, k;
    if (radix == 10 && num < 0) {
        unum = (unsigned) -num;
        str[i++] = '-';
    } else unum = (unsigned) num;
    do {
        str[i++] = itoa_index[unum % (unsigned) radix];
        unum /= radix;
    } while (unum);
    str[i] = '\0';
    if (str[0] == '-') k = 1;
    else k = 0;
    char temp;
    for (j = k; j <= (i - k - 1) / 2.0; j++) {
        temp = str[j];
        str[j] = str[i - j - 1];
        str[i - j - 1] = temp;
    }
    return i;
}

uint8_t mystr_len(uint8_t *data) {
    uint8_t i = 0;
    while ((*data++) != '\0')
        i++;
    return i;
}

uint32_t myPow(uint32_t a, uint32_t b) {
    for (int i = 0; i < b; i++)a *= a;
    return a;
}

int32_t myatoi(uint8_t *str, uint8_t len, uint8_t radix) {
    uint32_t base = 1;
    int32_t result = 0;
    for (int i = len - 1; i >= 0; i--) {
        if (i == 0) {
            if (*(str) == '-') {
                result = 0 - result;
                break;
            }
        }
        uint8_t b = 0;
        if (radix <= 10) {
            b = *(str + i) - 48;
            if (b > 9) {
                return 0;
            }
        } else {
            uint8_t tmp = *(str + i);
            if (tmp >= 48 && tmp <= 57) {
                b = tmp - 48;
            } else if (tmp >= 97 && tmp <= 122) {
                tmp -= 32;
            } else if (tmp >= 65 && tmp <= 65 + radix - 11) {
                b = tmp - 55;
            } else {
                return 0;
            }
        }

        result += b * base;
        base *= radix;
    }
    return result;
}

uint8_t myitoaFixLen(int32_t num, uint8_t *str, uint8_t radix, uint8_t len) {

    int length = myitoa(num, str, radix);
    if (length >= len)return length;
    memcpy(str + (length - 1), str, length);
    memset(str, '0', length - 1);


}